// pages/integral-records/integral-records.js
const { getIntegralRecords } = require("../../api/integral.js");

Page({
  data: {
    loading: false,
    hasMore: true,
    pageIndex: 1,
    pageSize: 20,
    recordsList: [],
    total: 0,
  },

  onLoad(options) {
    this.loadIntegralRecords(true);
  },

  onShow() {
    // 页面显示时刷新数据
    this.setData({
      pageIndex: 1,
      recordsList: [],
      hasMore: true,
    });
    this.loadIntegralRecords(true);
  },

  /**
   * 加载积分收支记录
   */
  async loadIntegralRecords(isRefresh = false) {
    if (this.data.loading) return;

    try {
      this.setData({ loading: true });

      const params = {
        pageIndex: isRefresh ? 1 : this.data.pageIndex,
        pageSize: this.data.pageSize,
      };

      const response = await getIntegralRecords(params);

      if (response.code === 0) {
        const { list, total, hasNextPage } = response.data;

        this.setData({
          recordsList: isRefresh ? list : [...this.data.recordsList, ...list],
          total: total,
          hasMore: hasNextPage,
          pageIndex: isRefresh ? 2 : this.data.pageIndex + 1,
        });
      } else {
        wx.showToast({
          title: response.message || "加载失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("加载积分记录失败:", error);
      wx.showToast({
        title: "加载失败，请重试",
        icon: "none",
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadIntegralRecords(false);
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.setData({
      pageIndex: 1,
      recordsList: [],
      hasMore: true,
    });
    this.loadIntegralRecords(true).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 格式化积分类型
   */
  formatIntegralType(type) {
    const typeMap = {
      1: "充值",
      2: "消费",
      3: "奖励",
      4: "退款",
      5: "提现",
      6: "过期",
      7: "调整",
      8: "取消订单退回",
    };
    return typeMap[type] || "未知";
  },

  /**
   * 格式化积分显示
   */
  formatPoints(points) {
    if (points > 0) {
      return `+${points}`;
    }
    return points.toString();
  },

  /**
   * 格式化时间
   */
  formatTime(timeStr) {
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) {
      return "今天";
    } else if (days === 1) {
      return "昨天";
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return timeStr.split(" ")[0];
    }
  },
});
